package com.bst.datatx.core.util;

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OperatingSystem;

public class OSUtils {
    private static final SystemInfo SI = new SystemInfo();
    public static double cpuUsage() {
        CentralProcessor processor = SI.getHardware().getProcessor();
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        // 建议间隔1秒获取更准确结果
        try { Thread.sleep(1000); } catch (InterruptedException e) {}
        double cpuUsage = processor.getSystemCpuLoadBetweenTicks(prevTicks);
        return Double.parseDouble(String.format("%.2f", cpuUsage * 100));
    }

    public static double memoryUsage() {
        GlobalMemory memory = SI.getHardware().getMemory();
        double ratio = (memory.getTotal() - memory.getAvailable()) * 1.0 / memory.getTotal();
        return Double.parseDouble(String.format("%.2f", ratio * 100));
    }
    private static HardwareAbstractionLayer hal = SI.getHardware();
    // 系统负载（6.8+新写法）
    public static double loadAverage1() {
        double[] aa = new SystemInfo().getHardware().getProcessor().getSystemLoadAverage(60);
        return aa[0];
    }

    public static double loadAverage() {
        // 优先使用CPU负载百分比(跨平台兼容)
        return SI.getHardware().getProcessor().getSystemCpuLoad(2000) * 100;
    }

}
